//
//  GroupMemberListViewController.m
//  GroupManager
//
//  Created by 欧阳 鹏 on 11-10-18.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "GroupMemberListViewController.h"
#import "GMPerson.h"
#import "ABManager.h"
#import "RootViewController.h"
#import "SMSViewController.h"
#import "MailViewController.h"

extern GADBannerView *bannerView_;


@implementation GroupMemberListViewController

@synthesize group, groupID, rootViewController, tableView = _tableView;


#pragma mark -
#pragma mark View lifecycle


- (void)viewDidLoad {
    [super viewDidLoad];
	self.navigationItem.title = NSLocalizedString(@"members", nil);
	addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addMembers)];
	self.navigationItem.rightBarButtonItem = self.editButtonItem;
	groupID = ABRecordGetRecordID(group.group);
	
	CGRect frame = self.tableView.frame;
	self.tableView.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, frame.size.height - GAD_SIZE_320x50.height);
	NSLog(@"%f", self.tableView.frame.size.height);
	
	[[NSNotificationCenter defaultCenter] addObserver:self 
											 selector:@selector(reload) 
												 name:UIApplicationDidBecomeActiveNotification 
											   object:[UIApplication sharedApplication]];

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}



- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
	//[self.tableView reloadData];
	if (bannerView_) {
		[UIView beginAnimations:nil context:nil];
		[bannerView_ setFrame:CGRectMake(0.0,
										 self.navigationController.view.frame.size.height -
										 GAD_SIZE_320x50.height - 44,
										 GAD_SIZE_320x50.width,
										 GAD_SIZE_320x50.height)];
		[UIView commitAnimations];
	}
}

/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/


#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [group.persons count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    // Configure the cell...
	NSString* name;
	GMPerson *person = [group.persons objectAtIndex:indexPath.row];
	name = [(NSString*)ABRecordCopyCompositeName(person.person) autorelease];
	cell.accessoryType = UITableViewCellAccessoryNone;
	cell.textLabel.text = name;
    
    return cell;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/



// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source.
		[group removeMemberAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
		[rootViewController.tableView reloadData];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }   
}



/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
    /*
    <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
    // ...
    // Pass the selected object to the new view controller.
    [self.navigationController pushViewController:detailViewController animated:YES];
    [detailViewController release];
    */
	ABPersonViewController *pvc = [[ABPersonViewController alloc] init];
	pvc.displayedPerson = [(GMPerson*)[group.persons objectAtIndex:indexPath.row] person];
	pvc.personViewDelegate = self;
	[pvc setAllowsEditing:YES];
	[pvc performSelector:@selector(setAllowsActions:) withObject:(id)YES];
	[self.navigationController pushViewController:pvc animated:YES];
	[pvc release];
	[self.tableView deselectRowAtIndexPath:indexPath animated:YES];
	if (bannerView_) {
		[UIView beginAnimations:nil context:nil];
		[bannerView_ setFrame:CGRectMake(0.0,
										 self.navigationController.view.frame.size.height,
										 GAD_SIZE_320x50.width,
										 GAD_SIZE_320x50.height)];
		[UIView commitAnimations];
	}
}
/*
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
	ABPersonViewController *pvc = [[ABPersonViewController alloc] init];
	pvc.displayedPerson = [(GMPerson*)[group.persons objectAtIndex:indexPath.row] person];
	pvc.personViewDelegate = self;
	[pvc setAllowsEditing:YES];
	[pvc setAllowsActions:YES];
	[self.navigationController pushViewController:pvc animated:YES];
	[pvc release];
}
*/

#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
	[rootViewController release];
	[addButton release];
	[group release];
	[_tableView release];
	[[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];
}

- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
	[super setEditing:editing animated:animated];
	[self.tableView setEditing:editing animated:animated];
	if (editing) {
		self.navigationItem.leftBarButtonItem = addButton;
	} else {
		self.navigationItem.leftBarButtonItem = self.navigationItem.backBarButtonItem;
	}
}

#pragma mark -
#pragma mark ABPeoplePickerNavigationControllerDelegate

- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker {
	[peoplePicker dismissModalViewControllerAnimated:YES];
}

- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person {
	ABRecordID personID = ABRecordGetRecordID(person);
	ABRecordRef personCopy = ABAddressBookGetPersonWithRecordID([ABManager sharedManager].addressBook, personID);
	[group addMember:personCopy];
	NSString *name = [(NSString*)ABRecordCopyCompositeName(personCopy) autorelease];
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Info", nil) 
													message:[NSString stringWithFormat:NSLocalizedString(@"Person Added Format", nil), name] 
												   delegate:nil cancelButtonTitle:NSLocalizedString(@"ok", nil) otherButtonTitles:nil];
	[alert show];
	[alert release];
	[self.tableView reloadData];
	return NO;
}

- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier {
	return YES;
}

#pragma mark -
#pragma mark ABPersonViewControllerDelegate

- (BOOL)personViewController:(ABPersonViewController *)personViewController shouldPerformDefaultActionForPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifierForValue {
	return YES;
}

#pragma mark -
#pragma mark UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
	switch (buttonIndex) {
		case 0:
		{
			MailViewController *mvc = [[MailViewController alloc] initWithNibName:@"MailViewController" bundle:nil];
			mvc.group = group;
			[self.navigationController pushViewController:mvc animated:YES];
			[mvc release];
			if (bannerView_) {
				[UIView beginAnimations:nil context:nil];
				[bannerView_ setFrame:CGRectMake(0.0,
												 self.navigationController.view.frame.size.height,
												 GAD_SIZE_320x50.width,
												 GAD_SIZE_320x50.height)];
				[UIView commitAnimations];
			}
			break;
		}
		case 1:
		{
			SMSViewController *svc = [[SMSViewController alloc] initWithNibName:@"SMSViewController" bundle:nil];
			svc.group = group;
			[self.navigationController pushViewController:svc animated:YES];
			[svc release];
			if (bannerView_) {
				[UIView beginAnimations:nil context:nil];
				[bannerView_ setFrame:CGRectMake(0.0,
												 self.navigationController.view.frame.size.height,
												 GAD_SIZE_320x50.width,
												 GAD_SIZE_320x50.height)];
				[UIView commitAnimations];
			}
			break;
		}
		default:
			break;
	}
}

#pragma mark -
#pragma mark Custom Operations

- (void)addMembers {
	ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationController alloc] init];
    picker.peoplePickerDelegate = self;
    [self presentModalViewController:picker animated:YES];
    [picker release];
}

- (void)sendMailOrSms {
	UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:NSLocalizedString(@"Select your operation", nil) 
													   delegate:self 
											  cancelButtonTitle:NSLocalizedString(@"cancel", nil)
										 destructiveButtonTitle:nil
											  otherButtonTitles:NSLocalizedString(@"Send Mail", nil), NSLocalizedString(@"Send SMS", nil), nil];
	[sheet showInView:self.view];
	[sheet release];
}

- (void)reload {
	ABRecordRef _group = ABAddressBookGetGroupWithRecordID([ABManager sharedManager].addressBook, groupID);
	if (!_group) {
		[group.persons removeAllObjects];
		if (self.editing) {
			[self setEditing:NO animated:YES];
		}
		self.navigationItem.rightBarButtonItem = nil;
	} else {
		[group release];
		group = nil;
		for (GMGroup *gmg in [ABManager sharedManager].groups) {
			if (ABRecordGetRecordID(gmg.group) == groupID) {
				self.group = gmg;
			}
		}
	}
	[self.tableView reloadData];
}


@end

